package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.louwowo.cache.service.*;
import cn.wolfcode.louwowo.cache.vo.TravelStatisVO;
import cn.wolfcode.louwowo.cache.vo.VisitStatisVO;
import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.*;
import cn.wolfcode.luowowo.comment.domain.ScenicspotComment;
import cn.wolfcode.luowowo.comment.query.ScenicspotCommentQuery;
import cn.wolfcode.luowowo.comment.service.IScenicspotCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.BeanUtil;
import cn.wolfcode.luowowo.member.domain.PersonInfo;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IPersonInfoService;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("mine")
public class UserInfoController {
    @Reference
    private ITravelService travelService;
    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private ITravelStatisRedisService travelStatisRedisService;
    @Reference
    private IPersonInfoService personInfoService;
    @Reference
    private IStrategyService strategyService;
    @Reference
    private IStrategyStatisRedisService strategyStatisRedisService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IVisitStatisService visitStatisService;
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    @Reference
    private IScenicspotCommentService scenicspotCommentService;
    @Reference
    private IScenicStatisRedisService scenicStatisRedisService;
    @Reference
    private IScenicspotService scenicspotService;
    @Reference
    private ITicketService ticketService;

    /**
     * 我的窝的主页
     * @param model
     * @param userInfo
     * @return
     */
    @RequestMapping("homepage")
    @RequireLogin
    public String homePage(Model model,@UserParam UserInfo userInfo){
        //用户信息相关
        model.addAttribute("user",userInfo);
        page(model,userInfo.getId());
        return "mine/homepage";
    }



    @RequestMapping("travelcollection")
    public String travelcollection(Model model,@UserParam UserInfo userInfo,Long id){
        model.addAttribute("user",userInfo);
        //收藏的游记
        List<Long> tids = travelStatisRedisService.getCollection(userInfo.getId(),id);
        ArrayList<Travel> tlist = new ArrayList<>();
        for (Long tid : tids) {
            tlist.add(travelService.get(tid));
        }
        //收藏的攻略
        List<Long> sids = strategyStatisRedisService.getStrategyFavor(userInfo.getId(),id);
        List<StrategyDetail> strategyList =new ArrayList<>();
        for (Long sid : sids) {
            strategyList.add(strategyDetailService.get(sid));
        }
        //收藏的景点
        List<Long> favorList = scenicStatisRedisService.getFavorList(userInfo.getId());
        List<Scenicspot> scenicspots = new ArrayList<>();
        for (Long aLong : favorList) {
            scenicspots.add(scenicspotService.get(aLong));
        }
        model.addAttribute("travleFavor",tlist);
        model.addAttribute("strategyList",strategyList);
        model.addAttribute("scenicspots",scenicspots);
        return "mine/travelcollection";
    }



    /**
     * 我的游记
     * @ param model
     * @param userInfo
     * @return
     */

    @RequestMapping("mytravelnotes")
    public String travelNote(Model model, @UserParam UserInfo userInfo,@ModelAttribute("qo") TravelQuery qo){
        if (userInfo!=null) {
            qo.setUserId(userInfo.getId());
            //当前用户
            model.addAttribute("user",userInfo);
            int replynum=0;
            int viewnum=0;
            PageInfo<Travel> pageInfo = travelService.query(qo);

            TravelStatisVO vo=new TravelStatisVO();
            for (Travel travel : pageInfo.getList()) {
                Destination dest = destinationService.getDestById(travel.getDest().getId());
                travel.setDest(dest);
                vo = travelStatisRedisService.getStatisVo(travel.getId());
                //travel.setThumbsupnum(vo.getThumbsupnum());
                BeanUtil.copy(travel,vo);
                replynum += travel.getReplynum();
                viewnum += travel.getViewnum();

            }

            //回复数
            model.addAttribute("replynum",replynum);
            //阅读数
            model.addAttribute("viewnum",viewnum);
            model.addAttribute("pageInfo",pageInfo);
            //游记数
            model.addAttribute("travelNum",pageInfo.getTotal());

        }


        return "mine/mytravelnotes";
    }


    /**
     * 点赞操作
     * @param tid
     * @param userInfo
     * @return
     */

    @RequestMapping("travelThumbup")
    @ResponseBody
    public AjaxResult travelThumbup(Long tid, @UserParam UserInfo userInfo){
        //先判断是否登陆
        if(userInfo == null){
            return AjaxResult.UNLOGIN();
        }
        boolean b = travelStatisRedisService.thumbup(tid, userInfo.getId());
        //true表示是已顶过了，false表示今天还没顶
        return new AjaxResult(!b,"").getData(travelStatisRedisService.getStatisVo(tid));
    }


    @RequestMapping("otherspage")
    public String othersPage(Model model,Long id,@UserParam UserInfo user){
        model.addAttribute("user",userInfoService.get(id));
        //判断是否是关注
        if(user == null){
            model.addAttribute("isAttention",false);
        }else{

            model.addAttribute("isAttention",personInfoService.getAttentionById(user.getId(),id));
        }

        page(model,id);

        return "mine/otherspage";
    }

    public void page(Model model,Long id){

        //关注的用户和粉丝
        PersonInfo personInfo = personInfoService.getByUserId(id);
        if (personInfo!=null) {
            List<Long> ids = personInfo.getAttentionUserIds();
            ArrayList<UserInfo> list = new ArrayList<>();
            for (Long uid : ids) {
                UserInfo user = userInfoService.get(uid);
                list.add(user);
            }
            //访问数+1
            visitStatisService.numIncrease(id,1);
            VisitStatisVO vo1 = visitStatisService.dayNum(id, 1);
            VisitStatisVO vo = visitStatisService.getVisitStatisVo(id);
            personInfo.setVisitNum(vo.getVisitNum());
            personInfo.setDayNum(vo1.getDayNum());
            model.addAttribute("list",list);
            model.addAttribute("personInfo",personInfo);

            TravelStatisVO tvo=new TravelStatisVO();
            List<Travel> travels = travelService.getByUserId(id);
            for (Travel travel : travels) {
                //设置上级目的地
                Destination dest = destinationService.getDestById(travel.getDest().getId());
                travel.setDest(dest);

                tvo = travelStatisRedisService.getStatisVo(travel.getId());
                BeanUtil.copy(travel,tvo);
            }
            //游记数量
            model.addAttribute("travelNum",travels.size());
            //只显示按照阅读数排序的前三
            if(travels.size()>=3){
                model.addAttribute("travels",travels.subList(0,3));

            }else{
                model.addAttribute("travels",travels);
            }

            List<ScenicspotComment> scComments = scenicspotCommentService.listAllByUserId(id);
            if(scComments == null){
                model.addAttribute("scNum",0);
            }else{
                model.addAttribute("scNum",scComments.size());
            }


            //显示最近点评前三
            model.addAttribute("scComments",scenicspotCommentService.queryTop3(id));
        }


    }

    @RequireLogin
    @RequestMapping("/setting")
    public String setting(Model model, @UserParam UserInfo user){
        model.addAttribute("user",user);
        model.addAttribute("dests",destinationService.getDestByDeep(2));
        model.addAttribute("personinfo",personInfoService.getByUserId(user.getId()));
        return "mine/setting";
    }

    //保存用户信息
    @RequireLogin
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public AjaxResult saveOrUpdate(UserInfo user, HttpServletResponse resp, HttpServletRequest req){
        userInfoService.saveOrUpdate(user);
        userInfoRedisService.setToken(CookieUtil.getToken(req,resp),userInfoService.get(user.getId()));
        return new AjaxResult();
    }

    //用户头像
    @RequireLogin
    @RequestMapping("/updateUserHeadImg")
    @ResponseBody
    public AjaxResult updateUserHeadImg(String headImgUrl,@UserParam UserInfo user,HttpServletResponse resp, HttpServletRequest req){
        if(headImgUrl != null && headImgUrl.length()>0){
            user.setHeadImgUrl(headImgUrl);
            userInfoService.updateUserHeadImg(user);
            userInfoRedisService.setToken(CookieUtil.getToken(req,resp),user);
        }
        return new AjaxResult();
    }

    //用户密码更改
    @RequestMapping("/updatepasswordByPhone")
    @ResponseBody
    public AjaxResult updatepasswordByPhone(String phone,String newpassword,String verifyCode){
        userInfoService.updatePasswordByPhone(phone,newpassword,verifyCode);
        return new AjaxResult();
    }

    //用户邮箱验证
    @RequestMapping("/updateEmail")
    @ResponseBody
    public AjaxResult updateemail(Long id,String email,String verifyCode){
        userInfoService.updateEmailById(id,email,verifyCode);
        return new AjaxResult();
    }
    //验证邮箱是否已经注册过
    @RequestMapping("checkEmail")
    @ResponseBody
    public boolean checkPhone(String email){
        return !userInfoService.checkEmail(email);
    }

    //发送验证码
    @RequireLogin
    @RequestMapping("sendEmailVerifyCode")
    @ResponseBody
    public AjaxResult sendEmailVerifyCode(@UserParam UserInfo userInfo, String email){
        if(email != null && userInfo.getEmail().equals(email)){
            userInfoService.sendEmailVerifyCode(email);
            return new AjaxResult();
        }
        return new AjaxResult(false,"请输入自己的邮箱,进行验证");
    }

    //用户手机号验证
    @RequireLogin
    @RequestMapping("/checkPhone")
    @ResponseBody
    public AjaxResult checkPhone(@UserParam UserInfo user, String phone,String code){
        if(phone != null && user.getPhone().equals(phone)){
            if(userInfoService.checkPhoneByVerifyCode(user.getId(),phone,code)){
                return new AjaxResult();
            }
        }
        return new AjaxResult(false,"请输入正确的手机号!");
    }

    //用户更换手机号
    @RequireLogin
    @RequestMapping("/updatePhone")
    @ResponseBody
    public AjaxResult updatePhone(@UserParam UserInfo user,HttpServletResponse resp, HttpServletRequest req, String phone,String code){
        if(phone != null){
            userInfoService.updatePhoneByVerifyCode(user.getId(),phone,code);
            userInfoRedisService.setToken(CookieUtil.getToken(req,resp),user);
            return new AjaxResult();
        }
        return new AjaxResult(false,"请输入正确的手机号!");
    }

    //用户注销
    @RequireLogin
    @RequestMapping("/delete")
    @ResponseBody
    public AjaxResult delete(@UserParam UserInfo user, String phone,String code){
        userInfoService.delete(user,phone,code);
        return new AjaxResult();

    }

    //我的点评
    @RequestMapping("/review")
    @RequireLogin
    public String review(Model model,@UserParam UserInfo user ,@ModelAttribute("qo") ScenicspotCommentQuery qo){
        qo.setUserId(user.getId());
        model.addAttribute("page",scenicspotCommentService.queryByUserId(qo));
        model.addAttribute("user",user);
        return "mine/review";
    }

    //关注
    @RequestMapping("/attention")
    @RequireLogin
    @ResponseBody
    public AjaxResult attention(Model model,@UserParam UserInfo user,Long id,int isatt){
        if(isatt == 0){
            personInfoService.updateAttentionByid(user.getId(),id,true);
            return new AjaxResult();
        }
        personInfoService.updateAttentionByid(user.getId(),id,false);
        return AjaxResult.UNLOGIN();
    }

}
